<?php
/**
 * Created by chency.
 * User: Administrator
 * Date: 2018/11/4 0004
 * Time: 下午 6:12
 */
namespace app\index\model;

use think\cache\driver\Redis;
use think\Db;
use think\Model;

class VisitedModel extends Model
{
    public $table = 'tps_visited';

    public static function create ($data = [], $field = null)
    {
        $data['url'] = self::getUrlId ($data['url'], true);
        if (!empty($data['referer'])) $data['referer'] = self::getUrlId ($data['referer'], false);
        else $data['referer'] = 0;
        return parent::create ($data, $field);
    }

    private static function getUrlId ($url = '', $inc = true)
    {
        preg_match ('/[\w][\w-]*\.(?:com\.cn|com|cn|co|net|org|gov|cc|biz|info|hs)(\/|$)/isU', $url, $domain);
        $data = [
            'url'    => $url,
            'domain' => $domain[0],
        ];
        //判断是否存在这个域名
        $his = Db::table ('tps_url')->field ('id,visit_times')->where ($data)->find ();
        if (!empty($his)) {
            if ($inc == true) $data['visit_times'] = $his['visit_times'] + 1;
            $data['last_visit_time'] = time ();
            $res = $his['id'];
            Db::table ('tps_url')->where (['id' => $his['id']])->update ($data);
        } else {
            $data['visit_times'] = 1;
            $data['first_visit_time'] = time ();
            $data['last_visit_time'] = time ();
            $res = Db::table ('tps_url')->insert ($data);
        }
        return $res;
    }
}